package org.shop.controller.app;

import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shop.entity.Goods;
import org.shop.entity.GoodsAppraises;
import org.shop.entity.Orders;
import org.shop.service.GoodsAppraisesService;
import org.shop.service.GoodsService;
import org.shop.service.OrdersService;
import org.shop.util.CommonUtil;
import org.shop.util.DateUtils;
import org.shop.util.FtpUtil2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@Controller
public class GoodsAppraisesController {
	
	private static Logger logger = LogManager.getLogger(GoodsAppraisesController.class);
	
	@Autowired
    private GoodsAppraisesService goodsAppraisesService;
	@Autowired
	private OrdersService ordersService;
	
	/**
	 * 跳转到添加评论页面
	 * @param req
	 * @return
	 */
	@RequestMapping("app/toAddGoodsAppraises")
	public String toAddGoodsAppraises(HttpServletRequest req) {
		Long orderId = Long.parseLong(req.getParameter("orderId"));
		Long goodsId = Long.parseLong(req.getParameter("goodsId"));
		Orders orders = ordersService.selectByPrimaryKey(orderId);
		req.setAttribute("orders", orders);
		req.setAttribute("goodsId", goodsId);
		return "app/discuss";
	}
	
	
	/**
	 * 添加评论晒单
	 * @param req
	 * @return
	 */
	@RequestMapping("app/addGoodsAppraises")
	@ResponseBody
	public Map<String,Object> addGoodsAppraises(HttpServletRequest req){
		Map<String, Object> map=new HashMap<String, Object>();
    	String photoStr="";
    	String mainPhotoStr="";
		FTPClient ftpClient =null;
		try{
    		//创建一个通用的多部分解析器
//    		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(req.getSession().getServletContext());
    		//转换成多部分request  
//    		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)req;
//    		Long merchantId = Long.parseLong(req.getParameter("merchantId"));
    		Long orderId = Long.parseLong(req.getParameter("orderId"));
    		Long goodsId = Long.parseLong(req.getParameter("goodsId"));
    		Long merchantId = Long.parseLong(req.getParameter("merchantId"));
//    		Long goodsAttrId = Long.parseLong(multiRequest.getParameter("goodsAttrId"));
    		Long userId = Long.parseLong(req.getParameter("userId"));
    		Byte goodsScore = (byte) Integer.parseInt(req.getParameter("goodsScore"));
    		Byte serviceScore = (byte) Integer.parseInt(req.getParameter("serviceScore"));
    		Byte timeScore = (byte) Integer.parseInt(req.getParameter("timeScore"));
    		String content = req.getParameter("content");
    		//判断 request 是否有文件上传,即多部分请求
//    		if(multipartResolver.isMultipart(req)){
//    			//取得request中的所有文件名
//    			Iterator<String> iter = multiRequest.getFileNames();
//    			//创建ftp链接
//    			String ftp_photoDirectory="shop/image/" + DateUtils.toYmdX(new Date());
//    			ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
//    			while(iter.hasNext()){
//    				String name=iter.next();
//    				if(name.equals("goodsMainPhoto")){
//    					//取得上传文件
//        				List<MultipartFile> fileList = multiRequest.getFiles(name);
//        				if(fileList!=null){
//        					for(MultipartFile file:fileList){
//        						if(file != null){
//        							//取得当前上传文件的文件名称
//        	    					String myFileName = file.getOriginalFilename();
//        	    					myFileName=FtpUtil2.generateFileName(myFileName);
//        	    					//如果名称不为"",说明该文件存在，否则说明该文件不存在
//        	    					if(myFileName.trim() !=""){
//        	    						myFileName=FtpUtil2.generateFileName(myFileName);
//        	    						InputStream is = file.getInputStream();
//        	    						FtpUtil2.upload(myFileName, is, ftpClient);
//        	    						mainPhotoStr+=ftp_photoDirectory+"/"+myFileName;
//        	    					}
//        						}
//        					}
//        				}
//    				}else{
//    					//取得上传文件
//        				List<MultipartFile> fileList = multiRequest.getFiles(name);
//        				if(fileList!=null){
//        					for(MultipartFile file:fileList){
//        						if(file != null){
//        							//取得当前上传文件的文件名称
//        	    					String myFileName = file.getOriginalFilename();
//        	    					myFileName=FtpUtil2.generateFileName(myFileName);
//        	    					//如果名称不为"",说明该文件存在，否则说明该文件不存在
//        	    					if(myFileName.trim() !=""){
//        	    						myFileName=FtpUtil2.generateFileName(myFileName);
//        	    						InputStream is = file.getInputStream();
//        	    						FtpUtil2.upload(myFileName, is, ftpClient);
//        	    						if("".equals(photoStr)){
//        	    							photoStr+=ftp_photoDirectory+"/"+myFileName;
//        	    						}else{
//        	    							photoStr+=","+ftp_photoDirectory+"/"+myFileName;;
//        	    						}
//        	    					}
//        						}
//        					}
//        				}
//    				}
//    			}
//    		}
//    		finally {
//    		try {
//				if(ftpClient!=null){
//					FtpUtil2.closeConnection(ftpClient);
//				}
//			} catch (Exception e) {
//				ftpClient=null;
//			} 
//		}
  			GoodsAppraises goodsAppraises = new GoodsAppraises();
//			goodsAppraises.setMerchantId(merchantId);
			goodsAppraises.setOrderId(orderId);
			goodsAppraises.setUserId(userId);
			goodsAppraises.setGoodsId(goodsId);
			goodsAppraises.setMerchantId(merchantId);
//			goodsAppraises.setGoodsAttrId(goodsAttrId);
			goodsAppraises.setGoodsScore(goodsScore);
			goodsAppraises.setServiceScore(serviceScore);
			goodsAppraises.setTimeScore(timeScore);
			goodsAppraises.setContent(content);
//			goodsAppraises.setAppraisesAnnex(photoStr);
			int num = goodsAppraisesService.insertSelective(goodsAppraises);
			if(num>0) {
				Orders orders = new Orders();
				orders.setOrderId(orderId);
				orders.setIsAppraises((byte)1);
				ordersService.updateByPrimaryKeySelective(orders);
			}
			map.put("state", num);
			map.put("msg", "评论晒单成功");
		}catch(Exception e){
    		e.printStackTrace();
    		logger.error(e);
    		map.put("state", 0);
    		map.put("msg", "评论晒单失败");
    	}
		return map;
	}
	
	
	
	
}
